package opens.components.http;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.http.HttpResponse;

import com.idreems.zakerlike.util.Util;

import opens.components.cache.Cache;
import opens.components.cache.serializers.BitmapSerializer;
import opens.components.cache.serializers.CacheSerializer;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

public class ImageRequest extends HttpObjectRequest<Bitmap> {

    protected void onHttpResponseReceived(HttpResponse response) throws Exception {
        Bitmap responseBitmap = BitmapFactory.decodeStream(response.getEntity().getContent());
        setResponseObject(responseBitmap);
    }

    // Cache support
    protected CacheSerializer getCacheSerializer() {
        return BitmapSerializer.instance();
    }

    /**
     * 将cache中的数据另存为图像文件
     * 
     * @param file
     * @return
     */
    public boolean saveCache2File(String fileName) {
        if(Util.fileExist(fileName))
        {
            return true;
        }
        CacheSerializer cacheSerializer = getCacheSerializer();
        Cache cache = getCache();
        if (cache != null && cacheSerializer != null) { // try to get memento
                                                        // from cache
            Object cachedState = cache.get(getRequestCacheKey(), cacheSerializer);
            if (cachedState instanceof Bitmap) {
                Bitmap bitmap = (Bitmap) cachedState;
                // save as file
                ByteArrayOutputStream bytes = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, bytes);
                File f = new File(fileName);
                try {
                    f.createNewFile();
                    FileOutputStream fo = new FileOutputStream(f);
                    fo.write(bytes.toByteArray());
                    fo.close();
                    bytes.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return true;
            }
        }
        return false;
    }

}
